package com.base.app_core.base.impl;

import com.base.app_core.base.BaseView;
import com.base.app_core.base.BasicPressent;
import com.base.app_core.model.Configure;
import com.base.app_core.service.Retrofit.HttpResult;
import com.base.app_core.service.Retrofit.HttpUtils;
import com.base.app_core.service.Retrofit.RestServer;
import com.base.app_core.service.rx.Callback;
import com.base.app_core.util.log.F;

import java.lang.ref.WeakReference;

import javax.inject.Inject;

import io.reactivex.Observable;

/**
 * Created by quantan.liu on 2017/3/11.
 */
/*接口适配模式*/
public abstract class BasePresenter<T extends BaseView> implements BasicPressent<T> {
    protected WeakReference<T> mLifecycle;//防止内存泄漏
    protected RestServer mRestfull;
    private int TotalRequest = 1;
    private int hasFinish = 0;
    @Inject
    Configure configure;

    public T getView() {
        if (isnotNull())
            return mLifecycle.get();
        else
            return null;
    }

    public BasePresenter(T mLifecycle) {
        this.mLifecycle = new WeakReference<T>(mLifecycle);
    }

    public BasePresenter(RestServer mRestfull) {
        this.mLifecycle = new WeakReference<T>(null);
        this.mRestfull = mRestfull;
    }

    public void setmRestfull(RestServer mRestfull) {
        F.j("mrestfull==null:" + (mRestfull == null));
        this.mRestfull = mRestfull;
    }

    public <T> void invoke(Observable<HttpResult<T>> observable, Callback<T> callback) {
        if (mLifecycle.get() != null) {
            callback.setPressenter(this);
            HttpUtils.invoke(mLifecycle.get(), observable, callback);
        }
    }

    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在 {@link } 之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token 从服务端获取的用户身份令牌（Token）。
     * @return RongIM  客户端核心类的实例。
     */
    public void connect(String token) {

    }

    @Override
    public void attachView(T view) {
        this.mLifecycle = new WeakReference<T>(view);
    }

    public boolean isnotNull() {
        return mLifecycle != null && mLifecycle.get() != null;
    }

    public void addReqFinish() {
        this.hasFinish++;
        if (hasFinish >= TotalRequest) {
            if (isnotNull()) {
//                mLifecycle.get().setState(AppConstants.STATE_SUCCESS);
            }
        }
    }

    public int getHasFinish() {
        return hasFinish;
    }

    public void setTotalRequest(int totalRequest) {
        TotalRequest = totalRequest;
    }

    public int getTotalRequest() {
        return TotalRequest;
    }

}
